package weibo.model;

import java.util.Date;
import java.util.Vector;

import net.rim.device.api.i18n.SimpleDateFormat;

import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;

import code.Function;

import weibo.http.Response;

public class User extends WeiboResponse
{
	private String id;                      //用户UID
	private String screenName;            //微博昵称
	private String name;                  //友好显示名称，如Bill Gates,名称中间的空格正常显示(此特性暂不支持)
	private int province;                 //省份编码（参考省份编码表）
	private int city;                     //城市编码（参考城市编码表）
	private String location;              //地址
	private String description;           //个人描述
	private String url;                   //用户博客地址
	private String profileImageUrl;       //自定义图像
	private String userDomain;            //用户个性化URL
	private String gender;                //性别,m--男，f--女,n--未知
	private int followersCount;           //粉丝数
	private int friendsCount;             //关注数
	private int statusesCount;            //微博数
	private int favouritesCount;          //收藏数
	private Date createdAt;               //创建时间
	//private boolean following;            //保留字段,是否已关注(此特性暂不支持)
	private boolean verified;             //加V标示，是否微博认证用户
	private int verifiedType;             //认证类型
	private boolean allowAllActMsg;       //是否允许所有人给我发私信
	private boolean allowAllComment;      //是否允许所有人对我的微博进行评论
	private boolean followMe;             //此用户是否关注我
	private String avatarLarge;           //大头像地址
	private int onlineStatus;             //用户在线状态
	private Status status;         //用户最新一条微博
	private int biFollowersCount;         //互粉数
	private String remark;                //备注信息，在查询用户关系时提供此字段。
	private String lang;                  //用户语言版本
	private String verifiedReason;		  //认证原因
	private String weihao;				  //微號
	//private String statusId;
	private Vector trends;                //话题
	private byte[] avatarData=null;
		
	public Vector getTrends() {return trends;}
	public String getWeihao() {return weihao;}
	public String getVerifiedReason() {return verifiedReason;}
	//public String getStatusId() {return statusId;}
	public String getUrl() {return url;}
	public String getProfileImageUrl() {return profileImageUrl;}
	public int getVerifiedType() {return verifiedType;}
	
	public void setTrends(Vector trends) {this.trends=trends;}
	public void setWeihao(String weihao) {this.weihao = weihao;}
	public void setCreatedAt(Date createdAt) {this.createdAt = createdAt;}
	public void setVerifiedReason(String verifiedReason) {this.verifiedReason = verifiedReason;}
	//public void setStatusId(String statusId) {this.statusId = statusId;}

	public boolean isAllowAllActMsg() {return allowAllActMsg;}
	public boolean isAllowAllComment() {return allowAllComment;}
	public boolean isFollowMe() {return followMe;}
	public String getAvatarLarge() {return avatarLarge;}
	public int getOnlineStatus() {return onlineStatus;}
	public int getBiFollowersCount() {return biFollowersCount;}

	public void setAvatarData(byte[] data) {this.avatarData=data;}
	public byte[] getAvatarData() {return avatarData;}
	
	public User(JSONObject json) throws WeiboException
	{
		super();
		init(json);
	}

	private void init(JSONObject json) throws WeiboException
	{
		if(json!=null){
			try {
				id = json.getString("id");
				screenName = json.getString("screen_name");
				name = json.getString("name");
				province = json.getInt("province");
				city = json.getInt("city");
				location = json.getString("location");
				description = json.getString("description");
				url = json.getString("url");
				profileImageUrl = json.getString("profile_image_url");
				userDomain = json.getString("domain");
				gender = json.getString("gender");
				followersCount = json.getInt("followers_count");
				friendsCount = json.getInt("friends_count");
				favouritesCount = json.getInt("favourites_count");
				statusesCount = json.getInt("statuses_count");
				//SimpleDateFormat sdf=new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
				createdAt = parseDate(json.getString("created_at"));//, "EEE MMM dd HH:mm:ss z yyyy");
				//following = getBoolean("following", json);
				verified = getBoolean("verified", json);
				verifiedType = json.getInt("verified_type"); 
				verifiedReason = json.getString("verified_reason");
				allowAllActMsg = json.getBoolean("allow_all_act_msg");
				allowAllComment = json.getBoolean("allow_all_comment");
				followMe = json.getBoolean("follow_me");
				avatarLarge = json.getString("avatar_large");
				onlineStatus = json.getInt("online_status");
				//statusId = json.getString("status_id");
				biFollowersCount = json.getInt("bi_followers_count");
				if(!json.getString("remark").equals("")){remark = json.getString("remark");}
				lang = json.getString("lang");
				weihao = json.getString("weihao");
				if(!json.isNull("status"))
				{
					status = new Status(json.getJSONObject("status"));
				}
			} catch (JSONException jsone) {
				try {
					throw new WeiboException(jsone.toString(), json, 0);
				} catch (JSONException e) {}
			}
		}
	}
	
	public static UserWapper constructWapperUsers(Response res) throws WeiboException
	{
		JSONError error=new JSONError(res.asString());
		if(error.getErrorCode()!=0) {Function.errorDialog(error.toString()); return new UserWapper(new Vector());}
		
		JSONObject jsonUsers = res.asJSONObject();
		
		try {
			JSONArray user = jsonUsers.getJSONArray("users");
			int size = user.length();
			Vector users = new Vector(size);
			
			for (int i = 0; i < size; i++) {
				users.addElement(new User(user.getJSONObject(i)));
			}
			
			//long previousCursor = jsonUsers.getLong("previous_curosr");
			//long nextCursor = jsonUsers.getLong("next_cursor");
			//long totalNumber = jsonUsers.getLong("total_number");
			//String hasvisible = jsonUsers.getString("hasvisible");
			
			return new UserWapper(users);//, previousCursor, nextCursor,totalNumber,hasvisible);
		} catch (JSONException jsone) {
			throw new WeiboException(jsone.toString());
		}
	}

	public String getId() {return id;}
	public String getScreenName() {return screenName;}
	public String getName() {return name;}
	public int getProvince() {return province;}
	public int getCity() {return city;}
	public String getLocation() {return location;}
	public String getDescription() {return description;}

	public String getUserDomain() {return userDomain;}
	public String getGender() {return gender;}
	public int getFollowersCount() {return followersCount;}
	public int getFriendsCount() {return friendsCount;}
	public int getStatusesCount() {return statusesCount;}
	public int getFavouritesCount() {return favouritesCount;}
	
	public String getCreatedAtLong()
	{
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
		
		return sdf.formatLocal(createdAt.getTime());
	}

	public String getCreatedAtShort()
	{
		SimpleDateFormat sdf=new SimpleDateFormat("M/d HH:mm");
		
		return sdf.formatLocal(createdAt.getTime());
	}

	//public boolean isFollowing() {return following;}
	public boolean isVerified() {return verified;}
	public Status getStatus() {return status;}
	public String getRemark() {return remark;}
	public String getLang() {return lang;}

	/**
	 * 取得中文性别
	 * @return 中文性别，包括 男、女和未知
	 */
	public String getUserGender()
	{
		String sex="未知";
		
		if(gender.equals("m"))
		{
			sex="男";
		} else if(gender.equals("f"))
		{
			sex="女";
		}
		
		return sex;
	}
	
	/**
	 * 取得用户在线状态
	 * @return 返回 在线或者离线
	 */
	public String getUserOnlineStatus()
	{
		return (onlineStatus==1) ? "在线" : "离线";
	}
	
	public int hashCode()
	{
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}

	public boolean equals(Object obj)
	{
		if(this == obj) return true;
		if(obj == null) return false;
		if(getClass() != obj.getClass()) return false;
		
		User other = (User) obj;
		if (id == null)
		{
			if (other.id != null) return false;
		} else if (!id.equals(other.id)) return false;
		
		return true;
	}
	
	public String toString() {
		return "\u2605User [" +
		"\n\u2022 id=" + id +
		"\n\u2022 screenName=" + screenName + 
		"\n\u2022 name="+ name +
		"\n\u2022 province=" + province + 
		"\n\u2022 city=" + city +
		"\n\u2022 location=" + location + 
		"\n\u2022 description=" + description + 
		"\n\u2022 url=" + url + 
		"\n\u2022 profileImageUrl=" + profileImageUrl + 
		"\n\u2022 userDomain=" + userDomain + 
		"\n\u2022 gender=" + gender + 
		"\n\u2022 followersCount=" + followersCount + 
		"\n\u2022 friendsCount=" + friendsCount + 
		"\n\u2022 statusesCount=" + statusesCount + 
		"\n\u2022 favouritesCount=" + favouritesCount + 
		"\n\u2022 createdAt=" + createdAt + 
		//"\n\u2022 following=" + following + 
		"\n\u2022 verified=" + verified + 
		"\n\u2022 verifiedType=" + verifiedType + 
		"\n\u2022 allowAllActMsg=" + allowAllActMsg + 
		"\n\u2022 allowAllComment=" + allowAllComment + 
		"\n\u2022 followMe=" + followMe + 
		"\n\u2022 avatarLarge=" + avatarLarge + 
		"\n\u2022 onlineStatus=" + onlineStatus + 
		"\n\u2022 status=" + status + 
		"\n\u2022 biFollowersCount=" + biFollowersCount + 
		"\n\u2022 remark=" + remark + 
		"\n\u2022 lang=" + lang +
		"\n\u2022 verifiedReason="  + verifiedReason +
		"\n\u2022 weihao=" + weihao +
		"\n\u2022 ]";
		//"\n\u2022 statusId=" + statusId;
	}
}